package com.corecmd.tcloud.tcim.ui.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.Nullable;

import com.corecmd.tcloud.tcim.R;
import com.corecmd.tcloud.tcim.apis.ApiLogin;
import com.corecmd.tcloud.tcim.common.Constant;
import com.corecmd.tcloud.tcim.common.LoginResultVO;
import com.corecmd.tcloud.tcim.common.RoundCornerButton;
import com.corecmd.tcloud.tcim.domain.ImLoginInfo;
import com.corecmd.tcloud.tcim.services.ImClientService;
import com.corecmd.tcloud.tcim.ui.main.MainActivity;
import com.corecmd.tcloud.tcim.utils.ToastUtil;

import static com.corecmd.tcloud.tcim.common.Constant.IM_LOGIN_INFO_SER_KEY;

/**
 * @author : TianShaoJiao
 * @date : 2021/3/2
 * @description :
 **/
public class LoginActivity extends Activity implements View.OnClickListener {
    private EditText mUserId;
    private EditText mPassword;
    private Context mContext;
    private RoundCornerButton mLoginBtn;
    private Handler mHandler;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        initEvent();
    }

    private void initEvent() {
        mLoginBtn.setOnClickListener(this);
    }

    private void initView() {
        mContext = this;
        mUserId = findViewById(R.id.login_userId);
        mPassword = findViewById(R.id.login_password);
        mLoginBtn = findViewById(R.id.btn_login);
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                if (message.what == R.id.btn_login){
                    LoginResultVO loginResultVO = (LoginResultVO)message.getData().getSerializable(Constant.IM_WEB_LOGIN_RESULT_INFO_KEY);
                    if (null != loginResultVO && "200".equalsIgnoreCase(loginResultVO.getStatusCode())
                            && !loginResultVO.getAuthToken().isEmpty()){
                        ToastUtil.showToaskShort(mContext,loginResultVO.getMessage());
                        SharedPreferences sp = getSharedPreferences(Constant.LOGININFOKEY, MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString(Constant.TOKENKEY,loginResultVO.getAuthToken());
                        editor.putString(Constant.IMHOST,loginResultVO.getImHost());
                        editor.putInt(Constant.IMPORT,loginResultVO.getImPort());
                        editor.putString(Constant.IMUSERID,loginResultVO.getUserId());
                        editor.apply();
                        //启动im登录service
                        start_im_service(loginResultVO.getUserId(),loginResultVO.getImHost(),loginResultVO.getImPort());
                        // 跳转到主页面
                        Intent it = new Intent(mContext, MainActivity.class);
                        startActivity(it);
                    } else {
                        ToastUtil.showToaskShort(mContext,loginResultVO.getMessage());
                    }
                }
                return false;
            }
        });
    }
    private void start_im_service(String userId,String imHost,int imPort){
        if (null != userId && !userId.isEmpty() && null != imHost && !imHost.isEmpty() && imPort != 0){
            Intent intent = new Intent(getBaseContext(), ImClientService.class);
            Bundle clientInfo = new Bundle();
            ImLoginInfo imLoginInfo = new ImLoginInfo();
            imLoginInfo.setUserId(userId);
            imLoginInfo.setImHost(imHost);
            imLoginInfo.setImPort(imPort);
            clientInfo.putSerializable(IM_LOGIN_INFO_SER_KEY,imLoginInfo);
            intent.putExtras(clientInfo);
            startService(intent);
        } else {
            ToastUtil.showToaskShort(mContext,"im登录信息有误，您已和im服务器断开连接");
        }
    }
    @Override
    public void onClick(View view) {
        int evId = view.getId();
        if (evId == R.id.btn_login){
            if (validateLoginInfo()){
                try {
                    loginIm();
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToaskShort(mContext,"登录异常，请联系管理员");
                }
            } else {
                ToastUtil.showToaskShort(mContext,"请填写完整登录信息");
            }
        }

    }
    private boolean validateLoginInfo(){
        String userId = mUserId.getText().toString();
        String password = mPassword.getText().toString();
        return !userId.isEmpty() && !password.isEmpty();
    }
    private void loginIm(){
        String userId = mUserId.getText().toString();
        String password = mPassword.getText().toString();
        new Thread(new Runnable() {
            @Override
            public void run() {
                LoginResultVO loginResultVO = ApiLogin.login(userId,password);
                Message message = new Message();
                message.what = R.id.btn_login;
                Bundle bundle = new Bundle();
                bundle.putSerializable(Constant.IM_WEB_LOGIN_RESULT_INFO_KEY,loginResultVO);
                message.setData(bundle);
                mHandler.sendMessage(message);
            }
        }).start();
    }
}
